package 接口测试;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

public class AiThinker {

    public static void AIThinkAll(String massageASK) throws IOException {
        String apiUrl = "https://openai.imedicalai.com/imedway-ai/app-api/rag/open/v1/app/chat";
        String apiKey = "sk-5a34ae62273949bd8cec1a60077c10b3";
        String appId = "2b3d38d30a95164984969fd9af7f3f0a";

        URL url = new URL(apiUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Api-Key", apiKey);
        conn.setRequestProperty("App-Id", appId);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(0); // 启用分块传输以支持流式响应

        // 构造请求体
        String jsonInputString = String.format(
                "{\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}],\"temperature\":0.2}",
                massageASK);

        try (OutputStream os = conn.getOutputStream();
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
            writer.write(jsonInputString);
            writer.flush();
        }

        // 处理响应流
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        StringBuilder buffer = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        String fullResponse = buffer.toString();
        String[] parts = fullResponse.split("data:");

        StringBuilder outputBuffer = new StringBuilder();
        StringBuilder output123Buffer = new StringBuilder();
        StringBuilder thinkBuffer = new StringBuilder();

        for (String part : parts) {
            String rawData = part.trim();
            if (rawData.isEmpty() || rawData.equals("[DONE]")) continue;

            try {
                // 简单 JSON 解析，仅适用于你的特定结构
                String result = extractValue(rawData, "\"result\":\"", "\"");
                int thinkType = Integer.parseInt(extractValue(rawData, "\"thinkType\":", ","));

                if (result == null || result.isEmpty()) continue;

                String cleanedResult = result.replaceAll("[#*\\-]", "");

                if (thinkType == 2) {
                    outputBuffer.append(cleanedResult);
                    output123Buffer.append(result);
                    System.out.println("【output】: " + cleanedResult);
                    System.out.println("【output123】: " + result);
                } else if (thinkType == 1) {
                    thinkBuffer.append(result);
                    System.out.println("【wenti】: " + result);
                }

            } catch (Exception e) {
                System.err.println("JSON 解析失败: " + e.getMessage());
                System.err.println("原始内容: " + rawData);
            }
        }

        reader.close();
    }

    // 简单的字符串提取方法
    private static String extractValue(String json, String startStr, String endStr) {
        int startIndex = json.indexOf(startStr);
        if (startIndex == -1) return null;
        startIndex += startStr.length();
        int endIndex = json.indexOf(endStr, startIndex);
        if (endIndex == -1) endIndex = json.length();
        return json.substring(startIndex, endIndex);
    }

    // 主函数测试
    public static void main(String[] args) {
        try {
            AIThinkAll("健康教育处");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}